package com.hyving.summer.fxpic.ctrl;


import com.hyving.summer.fxpic.utils.PicTools;

import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javafx.stage.DirectoryChooser;
import javafx.stage.Window;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;
import java.util.*;


@Slf4j
public class MainCtrl implements Initializable {

    public Pane rootPane;

    public Button folderChooser;

    public Label path;

    public Button match;

    public Button reorder;

    public Label result;

    public Button merge;

    private String fileAbsolutePath="";

    private static List<String> ends =Arrays.asList("jpg","jpeg","png","gif","JPG","JPEG","PNG","GIF");

    private static float matchRate =95;

    public void initialize(URL location, ResourceBundle resources) {



        log.info("initialize: {}", location.getPath());

        match.setVisible(false);
        reorder.setVisible(false);
        merge.setVisible(false);
        result.setVisible(false);
        result.setWrapText(true);


    }

    public void onFolderChoose(ActionEvent actionEvent){
        Window window = rootPane.getScene().getWindow();
        DirectoryChooser fileChooser = new DirectoryChooser();

        File file = fileChooser.showDialog(window);

        String fileAbsolutePath = file == null ? "" : file.getAbsolutePath();
        this.fileAbsolutePath =fileAbsolutePath;

        path.setText(fileAbsolutePath);

        match.setVisible(true);
        reorder.setVisible(true);
        merge.setVisible(true);
    }

    @SneakyThrows
    public void onPicMatch(ActionEvent actionEvent){
        result.setVisible(true);
        result.setText("处理中......");

        Map<String,byte[]> fingerMap =new HashMap<>();
        List<String> fileList =new ArrayList<>();

        File folder =new File(fileAbsolutePath);
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    String name =file.getName();
                    String end ="";
                    if(name.lastIndexOf(".") !=-1 && name.lastIndexOf(".")!=0){
                        end =name.substring(name.lastIndexOf(".")+1);
                    }

                    if(ends.contains(end)){
                        BufferedImage image = ImageIO.read(file);
                        byte[] bytes = PicTools.hashValue(image);
                        fingerMap.put(name,bytes);
                        fileList.add(name);
                    }

                }
            }
        }

        String resultText ="共有图片 "+fileList.size()+" 张";
        int deleteCount=0;
        for(int i=0;i<fileList.size()-1;i++){
            String fileName =fileList.get(i);
            for(int j =i+1;j<fileList.size();j++){
                String comName =fileList.get(j);
                float f =PicTools.compare(fingerMap.get(fileName),fingerMap.get(comName));
                if(f>matchRate){
                    //相似度高
                    fileList.remove(j);
                    System.out.println(comName);

                    File deleteFile =new File(fileAbsolutePath+"\\"+comName);
                    deleteFile.delete();
                    deleteCount++;
                    j--;
                }

            }
        }

        resultText= resultText+"\n"
                +"删除图片 "+deleteCount+" 张";

        result.setText(resultText);
    }


    public static String getRandomString(int length){
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<length;i++){
            int number=random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    public void onReorder(ActionEvent actionEvent){

        result.setVisible(true);
        result.setText("处理中......");

        int i=1;
        String prefix =getRandomString(4);
        File folder =new File(fileAbsolutePath);
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    String name =file.getName();
                    String end ="";
                    if(name.lastIndexOf(".") !=-1 && name.lastIndexOf(".")!=0){
                        end =name.substring(name.lastIndexOf(".")+1);
                    }
                    if(ends.contains(end)){
                        File newFile =new File(fileAbsolutePath+"\\"+prefix+"-"+i+""+"."+end);
                        file.renameTo(newFile);
                        i++;
                    }
                }
            }
        }

        result.setText("重命名完成");
    }


    public void onMerge(ActionEvent actionEvent){
        result.setVisible(true);
        result.setText("处理中......");

        String prefix =getRandomString(4);

        File newFolder =new File(fileAbsolutePath+"\\"+prefix);
        newFolder.mkdir();



        File folder =new File(fileAbsolutePath);
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    File[] seconds = file.listFiles();
                    int j=0;
                    for(File secondFile : seconds){
                        if(secondFile.isFile()){
                            String name =secondFile.getName();
                            String end ="";
                            if(name.lastIndexOf(".") !=-1 && name.lastIndexOf(".")!=0){
                                end =name.substring(name.lastIndexOf(".")+1);
                            }

                            File newFile =new File(fileAbsolutePath+"\\"+prefix+"\\"+secondFile.getName());
                            if(newFile.exists()){
                                newFile =new File(fileAbsolutePath+"\\"+prefix+"\\"+file.getName()+"-"+j+"."+end);
                            }
                            secondFile.renameTo(newFile);
                            j++;
                        }
                    }
                }
            }
        }
        result.setText("合并完成");
    }
}
